'use client'

import React from 'react'
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Autoplay } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/autoplay';
import LazyImage from '@/components/LazyImage';

// 懒加载视频组件
const LazyVideo = React.forwardRef<HTMLVideoElement, {
    src: string;
    poster?: string;
    onPlay?: (videoElement: HTMLVideoElement) => void;
    onPause?: (videoElement: HTMLVideoElement) => void;
    style?: React.CSSProperties;
}>(({ src, poster, onPlay, onPause, style }, ref) => {
    const [inView, setInView] = React.useState(false);
    const videoRef = React.useRef<HTMLVideoElement | null>(null);
    const containerRef = React.useRef<HTMLDivElement | null>(null);

    // 合并 ref
    React.useImperativeHandle(ref, () => videoRef.current!, []);

    React.useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                if (entries[0].isIntersecting) {
                    setInView(true);
                    observer.disconnect();
                }
            },
            { threshold: 0.1, rootMargin: '100px' }
        );

        if (containerRef.current) {
            observer.observe(containerRef.current);
        }

        return () => {
            observer.disconnect();
        };
    }, []);

    return (
        <div ref={containerRef} style={style}>
            {inView ? (
                <video
                    ref={videoRef}
                    controls
                    poster={poster || ""}
                    onPlay={(e) => onPlay?.(e.currentTarget)}
                    onPause={(e) => onPause?.(e.currentTarget)}
                    style={{
                        width: '100%',
                        height: '100%',
                        objectFit: 'cover'
                    }}
                >
                    <source src={src} type="video/mp4" />
                    您的浏览器不支持视频播放。
                </video>
            ) : (
                <div 
                    style={{
                        width: '100%',
                        height: '100%',
                        backgroundImage: poster ? `url(${poster})` : undefined,
                        backgroundSize: 'cover',
                        backgroundPosition: 'center',
                        backgroundColor: '#f0f0f0',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                    }}
                >
                    {!poster && <div className="text-gray-400">视频加载中...</div>}
                </div>
            )}
        </div>
    );
});

LazyVideo.displayName = 'LazyVideo';

interface MediaItem {
    src: string;
    type: 'video' | 'image';
    poster?: string; // 视频封面图或图片alt文本
    alt?: string; // 图片alt文本
}

interface MediaCarouselProps {
    items: MediaItem[];
    // 轮播图尺寸配置
    width?: string | number;
    height?: string | number;
    centered?: boolean; // 是否居中显示
    // Swiper 配置
    slidesPerView?: number;
    spaceBetween?: number;
    // 自动轮播配置
    autoplay?: boolean; // 是否自动轮播
    autoplayDelay?: number; // 自动轮播间隔时间（毫秒）
    transitionSpeed?: number; // 轮播切换动画的持续时间（毫秒）
    pauseOnMouseEnter?: boolean; // 鼠标悬停时是否暂停自动轮播
    disableOnInteraction?: boolean; // 用户交互后是否禁用自动轮播
    // 媒体内容配置
    mediaHeight?: string | number;
    objectFit?: 'cover' | 'contain' | 'fill' | 'scale-down' | 'none';
}

export default function MediaCarousel({
    items,
    width = '100%',
    height = 'auto',
    centered = true,
    slidesPerView = 1,
    spaceBetween = 30,
    autoplay = false,
    autoplayDelay = 3000,
    transitionSpeed = 600,
    pauseOnMouseEnter = true,
    disableOnInteraction = true,
    mediaHeight = 'auto',
    objectFit = 'cover'
}: MediaCarouselProps) {
    const [currentPlayingVideo, setCurrentPlayingVideo] = React.useState<HTMLVideoElement | null>(null);
    const [inView, setInView] = React.useState(false);
    const videoRefs = React.useRef<(HTMLVideoElement | null)[]>([]);
    const carouselRef = React.useRef<HTMLDivElement | null>(null);

    // 懒加载观察器
    React.useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                if (entries[0].isIntersecting) {
                    setInView(true);
                    observer.disconnect();
                }
            },
            { threshold: 0.1, rootMargin: '50px' }
        );

        if (carouselRef.current) {
            observer.observe(carouselRef.current);
        }

        return () => {
            observer.disconnect();
        };
    }, []);

    const handleCarouselVideoPlay = (videoElement: HTMLVideoElement, index: number) => {
        // Pause the currently playing video if it's different from the new one
        if (currentPlayingVideo && currentPlayingVideo !== videoElement) {
            currentPlayingVideo.pause();
        }
        setCurrentPlayingVideo(videoElement);
    };

    const handleCarouselVideoPause = (videoElement: HTMLVideoElement) => {
        if (currentPlayingVideo === videoElement) {
            setCurrentPlayingVideo(null);
        }
    };

    // 处理尺寸值，支持数字和字符串
    const getStyleValue = (value: string | number) => {
        return typeof value === 'number' ? `${value}px` : value;
    };

    return (
        <div
            ref={carouselRef}
            className={`relative ${centered ? 'mx-auto' : ''}`}
            style={{
                width: getStyleValue(width),
                height: getStyleValue(height),
            }}
        >
            {!inView ? (
                // 占位符，显示第一个项目的封面或加载状态
                <div className="w-full h-full flex items-center justify-center bg-gray-100 rounded-lg">
                    {items[0]?.poster ? (
                        <img
                            loading='lazy'
                            src={items[0].poster}
                            alt="预览"
                            className="w-full h-full object-cover rounded-lg opacity-50"
                        />
                    ) : (
                        <div className="text-gray-400 text-lg">正在加载...</div>
                    )}
                </div>
            ) : (
                <Swiper
                    modules={autoplay ? [Navigation, Autoplay] : [Navigation]}
                    spaceBetween={spaceBetween}
                    slidesPerView={slidesPerView}
                    speed={transitionSpeed}
                    loop={items.length > 1}
                    autoplay={autoplay ? {
                        delay: autoplayDelay,
                        pauseOnMouseEnter: pauseOnMouseEnter,
                        disableOnInteraction: disableOnInteraction,
                    } : false}
                    navigation={{
                        nextEl: '.swiper-button-next-custom',
                        prevEl: '.swiper-button-prev-custom',
                        hideOnClick: false,
                    }}
                    className="w-full h-full [&_.swiper-button-next]:hidden [&_.swiper-button-prev]:hidden"
                    breakpoints={{
                        640: {
                            slidesPerView: Math.min(slidesPerView, 1),
                            spaceBetween: spaceBetween * 0.5,
                        },
                        768: {
                            slidesPerView: Math.min(slidesPerView, 2),
                            spaceBetween: spaceBetween * 0.7,
                        },
                        1024: {
                            slidesPerView: slidesPerView,
                            spaceBetween: spaceBetween,
                        },
                    }}
                >
                    {items.map((item, index) => (
                        <SwiperSlide key={index}>
                            {item.type === 'video' ? (
                                <LazyVideo
                                    src={item.src}
                                    poster={item.poster}
                                    onPlay={(videoElement: HTMLVideoElement) => handleCarouselVideoPlay(videoElement, index)}
                                    onPause={handleCarouselVideoPause}
                                    style={{
                                        width: '100%',
                                        height: getStyleValue(mediaHeight),
                                        objectFit: objectFit
                                    }}
                                    ref={(el: HTMLVideoElement | null) => { videoRefs.current[index] = el; }}
                                />
                            ) : (
                                <img
                                    loading='lazy'
                                    src={item.src}
                                    alt={item.alt || "轮播图片"}
                                    style={{
                                        width: '100%',
                                        height: getStyleValue(mediaHeight),
                                        objectFit: objectFit
                                    }}
                                />
                            )}
                        </SwiperSlide>
                    ))}
                </Swiper>
            )}

            {/* Custom Navigation Buttons - 只在加载后显示 */}
            {inView && (
                <>
                    <div className="swiper-button-prev-custom absolute left-4 top-1/2 -translate-y-1/2 z-10 w-12 h-12 bg-[rgba(0,0,0,0.5)] bg-opacity-20 rounded-full flex items-center justify-center cursor-pointer hover:bg-opacity-40 transition-all">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <polyline points="15,18 9,12 15,6"></polyline>
                        </svg>
                    </div>
                    <div className="swiper-button-next-custom absolute right-4 top-1/2 -translate-y-1/2 z-10 w-12 h-12 bg-[rgba(0,0,0,0.5)] bg-opacity-20 rounded-full flex items-center justify-center cursor-pointer hover:bg-opacity-40 transition-all">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <polyline points="9,18 15,12 9,6"></polyline>
                        </svg>
                    </div>
                </>
            )}
        </div>
    );
}